<?php

!defined('IN_HC') && exit('Misquoted');

// Common library
require FILE . 'lib/common.class.php';

// Config
require FILE . 'config/' . ENVIRONMENT . '.php';

$environment = ENVIRONMENT;
$config = config::$$environment;

// Show Error
ini_set('error_reporting', $config['error_reporting']);
ini_set('display_errors', $config['display_errors']);

/**
 * Running class
 */
class init
{
    public function __construct()
    {
        $this->run();
    }

    /**
     * Get and load controller
     */
    public function run()
    {
        isset($_SERVER['argv'][1]) && parse_str($_SERVER['argv'][1], $_GET);

        // Controller name
        $controlName = substr(common::request('c', 'G'), 0, 24);

        // Modules name
        $modulesName = substr(common::request('m'), 0, 24);
        $modulesPath = NULL;

        $isTransformModules = FALSE;

        if(!$modulesName && $controlName && strpos($controlName, '_'))
        {
            list($modulesName, $controlName) = explode('_', $controlName);
            $isTransformModules = TRUE;
        }

        if(!$controlName && $modulesName)
        {
            $controlName = $modulesName;
        }
        elseif($modulesName)
        {
            $modulesPath = "{$modulesName}/";
        }

        !$controlName && !$modulesName && $controlName = 'index';
        $action = substr(common::request('a', 'G'), 0, 36);
        !$action && $action = 'init';

        $host = !empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : NULL;
        
        if($host && $host == 't.ijoggers.com')
        {
            $controlName != 'show' && $controlName = 'show';
            $action == 'init' && $action = 'article';
        }

        // Action name
        $actionName = 'do' . $action;

        $controlFile = FILE . 'controller/' . $modulesPath . $controlName . '.php';
        $modulesName && $controlName = $modulesName . ucfirst($controlName);

        if(!is_file($controlFile))
        {
            @header('HTTP/1.0 404 Not Found');
            exit("<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>");
        }

        // Load controller
        require FILE . 'model/base.class.php';
        require $controlFile;
        $controlName .= 'Controller';
        $control = new $controlName;

        // Load action
        call_user_func(array($control, $actionName), array());            
    }

}

function __autoload($className)
{
    $classFile = FILE . 'lib/' . $className . '.class.php';

    if(file_exists($classFile))
    {
        include_once $classFile;
    }
}